package controller;

import POJO.Books;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import service.BooksService;
import util.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by 79430 on 2018/1/4.
 */
@Controller
@RequestMapping("/Book")
public class BooksController {


    @Resource
    private BooksService booksService;


    @RequestMapping("/index")
    public String sel( @RequestParam(value="a",required=false)  Integer a,
                       @RequestParam(value="b",required=false)  String b,
                       @RequestParam(value="pageIndex",required=false)  Integer pageIndex,Model model){
        //设置页面容量
        int pageSize =3;
        //当前页码
        int currentPageNo = 1;

        int totalCount=booksService.count(a,b);
        Page page=new Page();
        page.setPageSize(pageSize);
        page.setTotalCount(totalCount);
        if(pageIndex!=null){
            currentPageNo=pageIndex;

        }
        if(currentPageNo<1){
            currentPageNo=1;
        }else if(currentPageNo>totalCount&&totalCount!=0){
            currentPageNo=totalCount;
        }

        page.setCurrPageNo(currentPageNo);
        int pageNo=(page.getCurrPageNo()-1)*pageSize;
        List<Books> list= booksService.selAll(a,b,pageNo,pageSize);
        model.addAttribute("list",list);
        model.addAttribute("page",page);
        model.addAttribute("a",a);
        model.addAttribute("b",b);
        return "index";
    }

    @RequestMapping("/add")
    public String add(@ModelAttribute("book") Books book){

        return "/add";
    }
    @RequestMapping("/addSave")
    public String addSave(Books book,HttpSession session){
        book.setCreateDate(new Date());
        int result=booksService.add(book);

        session.setAttribute("result",result);
        return "redirect:/Book/index";
    }
    @RequestMapping("/selById")
    public String selectById( @RequestParam(value="bookId",required=false)  Integer bookId,Model model){
        Books book=booksService.selbyId(bookId);
        model.addAttribute("Books",book);
        return "update";
    }

    @RequestMapping("/update")
    public String updateById(Books book) {
        book.setCreateDate(new Date());
        int result = booksService.updateById(book);
        if (result > 0) {
            return "redirect:/Book/index";
        }
        return "update";


    }

    @RequestMapping("/delect")
    public String delectById(Books book) {

        int result = booksService.deleteById(book);
        if (result > 0) {
            return "redirect:/Book/index";
        }
        return "index";


    }
}
